<?php
class Mailing extends CI_Model {

	/*
	 * get mailings
	 */
	function getMailings(){
		$params = json_decode($_POST['params']);
		$query = $this->db->query('
			SELECT *
			FROM mailings
			WHERE id_parent = '.$params->id_node.'
			ORDER BY is_mailing, name');
		return $query->result();
	}
	
	/*
	 * get details
	 */
	function getDetails(){
		$params = json_decode($_POST['params']);
		$query = $this->db->get_where('mailings', array('id_node' => $params->id_node));
		return $query->result();
	}
	
	/*
	 * get recipients
	 */
	function getRecipients(){
		$params = json_decode($_POST['params']);
		$query = $this->db->get('mailings_recipients_'.$params->id_node, $params->limit, $params->limit * ($params->page-1));
		return $query->result();
	}

	/*
	 * save mailing
	 */
	function saveMailing(){
		$params = json_decode($_POST['params']);
		//$date_create = date('Y-m-d H:i:s');
		switch ($params->is_mailing){
			case 0:
				$query = $this->db->query('
					INSERT INTO mailings(name, is_mailing, date_create)
					VALUES ("' . $params->name . '", ' . $params->is_mailing . ', NOW())');
				break;
			case 1:
				$query = $this->db->query('
					INSERT INTO mailings(name, is_mailing, date_create)
					VALUES ("' . $params->name . '", ' . $params->is_mailing . ', NOW())');

					$this->createRecipientsTable($this->db->insert_id());
				break;
		}
		return $query;
	}
	
	/*
	 * remove mailing
	 */
	function removeMailing(){
		$params = json_decode($_POST['params']);
		$this->load->dbforge();
		echo $this->dbforge->drop_table('mailings_recipients_'.$params->id_node);
		$this->db->delete('mailings', array('id_node' => $params->id_node));
	}

	

	/*
	 * update mailing
	 */
	function updateDetails(){
		$params = json_decode($_POST['params']);
		$data = array(
			'name' => $params->name,
			'sender_email' => $params->sender_email,
			'sender_name' => $params->sender_name,
			'email_title' => $params->email_title
        );
		$this->db->where('id_node', $params->id_node);
		$query = $this->db->update('mailings', $data);
		return $query;
	}

	/*
	 * update content
	 */
	function updateContent(){
		$params = json_decode($_POST['params']);
		$data = array(
			'email_content' => $params->email_content
        );
		$this->db->where('id_node', $params->id_node);
		$query = $this->db->update('mailings', $data);
		return $query;
	}
	
	/*
	 * update recipient
	 */
	function updateRecipient($recipient){
		$params = json_decode($_POST['params']);
		$data = array(
			'sent' => 1,
            'date_sent' => date('Y-m-d H:i:s')
		);
		$this->db->where('id_email', $recipient->id_email);
		$query = $this->db->update('mailings_recipients_'.$params->id_node, $data);
		return $query;
	}

	/*
	 * create recipients table
	 */
	function createRecipientsTable($id){
		$query = $this->db->query('
			CREATE TABLE IF NOT EXISTS mailings_recipients_'.$id.'(
				id_email INT(10) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
				email VARCHAR(100) NOT NULL UNIQUE,
				sent TINYINT UNSIGNED NOT NULL DEFAULT 0,
				date_sent DATETIME
			)');
	}
	
	/*
	 * get recipients to send
	 */
	function getRecipientToSend(){
		$params = json_decode($_POST['params']);
		$query = $this->db->get_where('mailings_recipients_'.$params->id_node, array('sent' => 0), 1);
		return $query->result();
	}
	
	/*
	 * count recipients
	 */
	function countRecipients(){
		$params = json_decode($_POST['params']);
		return $this->db->count_all('mailings_recipients_'.$params->id_node);
	}
	
	/*
	 * count sended recipients
	 */
	function countSentRecipients(){
		$params = json_decode($_POST['params']);
		$this->db->select('COUNT(*) AS MyCount');
		$this->db->from('mailings_recipients_'.$params->id_node);
		$this->db->where('sent', 1);
		$query = $this->db->get();
		$result = $query->result();
		return $result[0]->MyCount;
	}

	/*
	 * add recipients
	 */
	function saveRecipients(){
		$params = json_decode($_POST['params']);
		$recipients = $this->csvreader->parse_text($params->recipients);
		$recipientsPrepared = array();
		foreach($recipients as $key => $value){
			// get recipient from "Email"
			if(isset($value["\"Email\""])){
				$email = $value["\"Email\""];
			}
			
			//remove "
			$emailPrepared = str_replace('"', '', $email);
			
			//check duplicates
			$duplicate = false;
			foreach($recipientsPrepared as $rpKey => $rpValue){
				if($emailPrepared == $rpValue['email']){
					$duplicate = true;
					break;
				}
			}
			if(!$duplicate){
				$recipientsPrepared[] = array('email' => $emailPrepared);
			}
		}
		
		
		return $this->db->insert_batch('mailings_recipients_' . $params->id_node, $recipientsPrepared);
	}
}